//
//  ListTableViewController.m
//  mpoi
//
//  Created by thomasho on 15/11/6.
//  Copyright © 2015年 thomasho. All rights reserved.
//

#import "ListTableViewController.h"
#import "DBData.h"
#import "Foundation_defines.h"
#import "NSString+expanded.h"
#import "SVProgressHUD.h"

@interface ListTableViewController ()
@property (nonatomic,strong) NSArray *dataArray;
@end

@implementation ListTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //    self.dataArray = @[@{@"name":@"陕西历史博物馆"}];
    self.dataArray = [DBData Select:tb_region Filelds:nil condition:@"isdelete = '0'"];
    [self.tableView reloadData];
    [self reloadData];
}
- (void)reloadData{
//    http://dev.skyf.org
    if (!self.dataArray.count) {
        NSString *requestTime = [[DBData Select:tb_region Filelds:nil condition:@"1=1 order by update_time desc limit 1 offset 0"].firstObject valueForKey:@"update_time"];
        [HttpRequest request:url_regionlist data:@{@"start_index":@0,@"page_size":@10000,@"update_time":requestTime?:kDefaultUpdateTime} block:^(id data, id error) {
            if(data){
                if([DBData ImportTb:tb_region data:data key:@"id"]){
                    self.dataArray = [DBData Select:tb_region Filelds:nil condition:@"isdelete = '0'"];
                    [self.tableView reloadData];
                }
            }else{
                [[[UIAlertView alloc] initWithTitle:@"网络数据加载失败" message:nil delegate:self cancelButtonTitle:@"下次" otherButtonTitles:@"重试", nil] show];
            }
        }];

    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.cancelButtonIndex == buttonIndex) {
        self.dataArray = [DBData Select:tb_region Filelds:nil condition:@"isdelete = '0'"];
        [self.tableView reloadData];
    }else{
        [self reloadData];
    }
}
#pragma mark - Actions
- (IBAction)refreshButtonClicked:(id)sender {
    self.dataArray = nil;
    [self reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  self.dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"list" forIndexPath:indexPath];
    NSDictionary *dict = self.dataArray[indexPath.row];
    //to do
    cell.textLabel.text = [dict valueForJSONStrKey:@"name"];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self updateRegionData:indexPath.row];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(NSNumber *)sender {
    if ([segue.destinationViewController respondsToSelector:@selector(setDataDict:)]) {
        [segue.destinationViewController setValue:self.dataArray[sender.integerValue] forKey:@"dataDict"];
    }
}
//下载景区下所有景点、文物、beacon增量更新数据
- (void)updateRegionData:(NSInteger)index {
    [SVProgressHUD showWithStatus:NSLocalizedString(@"正在加载...", nil)];

    //寻找当前景区关联的 景点表、景点设备表、文物表、文物设备表 最后更新时间
    //景点表
    NSArray *spots = [DBData Select:tb_spot Filelds:nil condition:SF(@"region_id='%@' order by update_time desc",self.dataArray[index][@"id"])];
    NSString *updateTime = [spots.firstObject valueForJSONStrKey:@"update_time"];
    if (spots.count) {
        //景点关联设备
        NSString *spotBeaconTime = [[DBData Select:tb_beacon Filelds:nil condition:SF(@"id in %@ order by update_time desc LIMIT 1 OFFSET 0",[spots valueForKey:@"beacon_id"])].firstObject valueForJSONStrKey:@"update_time"];
        if ([spotBeaconTime compare:updateTime] == NSOrderedDescending) {
            updateTime = spotBeaconTime;
        }
        //关联文物
        NSMutableArray *marray = [NSMutableArray array];
        for (NSNumber *number in [spots valueForKey:@"id"]) {
            [marray addObject:SF(@"'%@'", number)];
        }
        NSString *spotids = [marray componentsJoinedByString:@","];
        NSArray *relics = [DBData Select:tb_relic Filelds:nil condition:SF(@"spot_id in (%@) order by update_time desc", spotids)];
        NSString *relicUpdateTime = [relics.firstObject valueForJSONStrKey:@"update_time"];
        if ([relicUpdateTime compare:updateTime] == NSOrderedDescending) {
            updateTime = relicUpdateTime;
        }
        //文物关联设备
        NSString *relicBeaconTime = [[DBData Select:tb_spot Filelds:nil condition:SF(@"id in %@ order by update_time desc LIMIT 1 OFFSET 0",[relics valueForKey:@"beacon_id"])].firstObject valueForKey:@"update_time"];

        if([relicBeaconTime compare:updateTime]==NSOrderedDescending){
            updateTime = relicBeaconTime;
        }
    }

    @weakify_self
    [HttpRequest request:url_regiondetail data:
     @{@"region_id":self.dataArray[index][@"id"],
       @"start_index":@0,@"page_size":@10000,
       @"update_time":updateTime?:kDefaultUpdateTime}
                   block:^(id data, id error) {
                       [SVProgressHUD dismiss];
                       @strongify_self
                       if (data) {
                           NSArray *beacons = [data valueForKey:@"beacon"];
                           NSArray *relics = [data valueForKey:@"relic"];
                           NSArray *spots = [data valueForKey:@"spot"];
                           //确保全部导入成功
                           BOOL flag = YES;
                           if(beacons.count&&![DBData ImportTb:tb_beacon data:beacons key:@"id"]) {
                               flag = NO;
                           }
                           if(relics.count&&![DBData ImportTb:tb_relic data:relics key:@"id"]){
                               flag = NO;
                           }
                           if(spots.count&&![DBData ImportTb:tb_spot data:spots key:@"id"]){
                               flag = NO;
                           }
                       }

                       //验证是否有本地数据
                       if ([[DBData Select:tb_spot Filelds:nil condition:@"isdelete='0' LIMIT 1 OFFSET 0"] count]) {
                           dispatch_async(dispatch_get_main_queue(), ^{
                               [self performSegueWithIdentifier:@"museum" sender:@(index)];
                           });
                       }else{
                           [[Utility Share] alert:error?:NSLocalizedString(@"数据加载失败。", nil)];
                       }
                   }];
}
@end
